import 'package:intl/intl.dart';

/// 时间工具
class TimeUtil {
  /// 当前时间戳，毫秒
  static int currentTimeMillis() {
    return DateTime.now().millisecondsSinceEpoch;
  }

  /// 当前时间戳，纳秒
  static int nanoTime() {
    return DateTime.now().microsecondsSinceEpoch;
  }

  /// 获取days天前0点0分0秒的时间戳
  static int getDayBefore(int days) {
    var c = DateTime.now();
    c = c.add(Duration(
        days: -days,
        hours: -c.hour,
        minutes: -c.minute,
        seconds: -c.second,
        milliseconds: -c.millisecond));
    return c.millisecondsSinceEpoch;
  }

  /// 明天0点0分0秒的时间戳
  static int getTomorrow() {
    var c = DateTime.now();
    c = c.add(Duration(
        days: 1,
        hours: -c.hour,
        minutes: -c.minute,
        seconds: -c.second,
        milliseconds: -c.millisecond));
    return c.millisecondsSinceEpoch;
  }

  /// 获取今天0点0分0秒的时间戳
  static int getWeeOfToday() {
    var c = DateTime.now();
    c = c.add(Duration(
        hours: -c.hour,
        minutes: -c.minute,
        seconds: -c.second,
        milliseconds: -c.millisecond));
    return c.millisecondsSinceEpoch;
  }

  /// 获取友好提示时间
  ///
  /// [millis] 时间戳，毫秒
  ///
  /// 1秒内：刚刚
  /// 1分钟内：x秒前
  /// 1小时内：x分钟前
  /// 今天内：H:mm
  /// 昨天内：昨天 H:mm
  /// 其他：yyyy-MM-dd
  static String getFriendlyTimeSpanByNow(final int millis) {
    int now = DateTime.now().millisecondsSinceEpoch;
    int span = now - millis;
    if (span < 0) {
      return DateFormat('yyyy-MM-dd')
          .format(DateTime.fromMillisecondsSinceEpoch(millis));
    }
    if (span < 1000) {
      return "刚刚";
    } else if (span < 60 * 1000) {
      return "${span ~/ 1000}秒前";
    } else if (span < 60 * 60 * 1000) {
      return "${span ~/ (60 * 1000)}分钟前";
    }
    // 获取当天 00:00
    int wee = getWeeOfToday();
    if (millis >= wee) {
      return DateFormat('H:mm')
          .format(DateTime.fromMillisecondsSinceEpoch(millis));
    } else if (millis >= wee - 24 * 60 * 60 * 1000) {
      return "昨天 ${DateFormat('H:mm').format(DateTime.fromMillisecondsSinceEpoch(millis))}";
    } else {
      return DateFormat('yyyy-MM-dd')
          .format(DateTime.fromMillisecondsSinceEpoch(millis));
    }
  }
}
